package com.situ.store.controller;

/*
 * @Author Darling_达
 * @Create 2023-03-01 16:43
 * @Version 1.0
 */

import com.situ.store.util.ImageUtil;

import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/image")
public class ImageController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 返回值类型为image图片
        resp.setContentType("image/jpeg");
        // 禁止图片缓存
        resp.setHeader("Pragma", "No-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);

        ServletOutputStream sos = resp.getOutputStream();

        String code = ImageUtil.createCode(); // 随机生成验证码
        req.getSession().setAttribute("code", code); // 验证码写入session
        ImageIO.write(ImageUtil.image(code), "JPEG", sos); // 流写出图像

        // 释放资源
        sos.flush();
        sos.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

}
